package dao;

import common.User;
import util.SnowflakeIdGenerator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertUserToBase {
    private static Connection conn=DataBaseConnect.getConn();
    private static String sql="INSERT INTO account (id,password,name,phone,birthdate,number) VALUES(?,?,?,?,?,?)";
    private static PreparedStatement pstmt;
    static {
        try {
            pstmt=conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static boolean Register(User user){
        //为避免学号重复，如果添加失败，尝试3次
        for(int i=1;i<=3;i++){
            try {
                pstmt.setString(1,user.getId());
                pstmt.setString(2,user.getPwd());
                pstmt.setString(3,user.getName());
                pstmt.setString(4,user.getPhone());
                pstmt.setString(5,user.getBirth());
                String ID=SnowflakeIdGenerator.ID(10);
                pstmt.setString(6,ID);
                int count=pstmt.executeUpdate();
                if(count==1) {
                    System.out.println("用户添加成功");
                    user.setNumber(ID);
                    return true;
                }
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("添加用户失败");
            }
        }
        return false;
    }
}
